package com.ai.bitcoin.controller;

import com.ai.bitcoin.output.GeneralReponse;
import com.ai.bitcoin.service.AdService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/ad")
@Slf4j
@RestController
public class AdController extends CommonController {

    @Value("${asyncTimeout}")
    long asyncTimeout;

    @Autowired
    private AdService adService;

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity<String> handleException(HttpServletRequest request,
                                                  HttpServletResponse response, RuntimeException e) {
        log.info("", e);
        return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("SERVICE_UNAVAILABLE");
    }

    @RequestMapping(value = "/query", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public DeferredResult<String> query(final HttpServletRequest request) {
        DeferredResult<String> deferredResult = new DeferredResult<>(asyncTimeout);
        GeneralReponse response = adService.query();
        return deferredContent(deferredResult, JSONObject.fromObject(response));
    }
}
